<template>
  <div class="app-container">

        <div class="cbox">
              <el-form class="form" ref="flt" :rules="rules" :inline="true" size="mini">
                 
                    <el-form-item label="品牌名称:" prop="brandName">
                      <el-input   placeholder="请输入品牌名称" v-model="from.brandName" style="width:100%" clearable></el-input>
                    </el-form-item>
                  <el-form-item label-width="10px">
                        <el-button @click="searchType" type="primary">查询</el-button>
                      </el-form-item>
                </el-form>
            </div>
            <el-row :gutter="10" class="btn-area">
                <el-col :span="24">
                  <buttonName @clickEvent="clickEventDom"></buttonName>
                  <!-- <el-button size="mini" type="primary" plain v-if="isAuth('add')" @click="add">新增</el-button>
                  <el-button size="mini" type="primary" plain v-if="isAuth('del')"  @click="del('diong')">编辑</el-button>
                  <el-button size="mini" type="primary" plain v-if="isAuth('examine')" @click="examine">删除</el-button>

                  <el-button type="primary" icon="document" size="mini" v-if="isAuth('handleImport')" @click="handleImport" plain>
                    批量{{ $t('excel.import') }}货物品牌
                  </el-button>
                  <el-button type="primary" icon="document" v-if="isAuth('handleDownload')" @click="handleDownload"
                      :loading="downloadLoading" size="mini" plain >
                        下载模板
                  </el-button> -->
                </el-col>
            </el-row>
            <div class="table" ref="topType">
                  
                <div class="inner" ref="inner">
                    <el-table
                        :data="DetailedData"
                        border
                        :height="maxHeight"
                        :header-cell-style="{ textAlign: 'center' }"
                        highlight-current-row
                        @row-dblclick='rowdbClickA'
                        @row-click="rowClick">
                        <el-table-column size="mini" align="center" :index="indexMethod" type="index" show-overflow-tooltip  label="序号" width="100"></el-table-column>
                        <!-- <el-table-column size="mini" prop="fltUuid" show-overflow-tooltip label="企业编号"></el-table-column> -->

                        <!-- <el-table-column size="mini" prop="arbitrationType" show-overflow-tooltip label="仲裁类型"></el-table-column> -->
                        <el-table-column size="mini" align="center" prop="brandName" show-overflow-tooltip label="品牌名称"></el-table-column>
                        <el-table-column size="mini" align="center" prop="brandCode" show-overflow-tooltip label="品牌代码"></el-table-column>
                        <el-table-column size="mini" align="center" show-overflow-tooltip label="是否默认" prop="isdefault">
                            <template slot-scope="scope">
                              <div style="text-align: center;" v-if="scope.row.isdefault == 'Y'">
                                <el-checkbox v-model="checkedY" disabled></el-checkbox>
                              </div>
                              <div  style="text-align: center;" v-if="scope.row.isdefault == 'N'">
                                <el-checkbox v-model="checkedN" disabled></el-checkbox>
                              </div>
                            </template>
                          </el-table-column>
                        <el-table-column size="mini" align="center" show-overflow-tooltip label="是否有效" prop="iseffective">
                            <template slot-scope="scope">
                              <div style="text-align: center;" v-if="scope.row.iseffective == 'Y'">
                                <el-checkbox v-model="checkedY" disabled></el-checkbox>
                              </div>
                              <div  style="text-align: center;" v-if="scope.row.iseffective == 'N'">
                                <el-checkbox v-model="checkedN" disabled></el-checkbox>
                              </div>
                            </template>
                          </el-table-column>
                        <el-table-column size="mini" align="center" prop="creator" show-overflow-tooltip label="创建人"></el-table-column>
                        <el-table-column size="mini" align="center" prop="created" show-overflow-tooltip label="创建时间"></el-table-column>

                         <el-table-column size="mini" align="center" prop="lastmodifier" show-overflow-tooltip label="修改人"></el-table-column>
                          <el-table-column size="mini" align="center" prop="lastmodified" show-overflow-tooltip label="修改时间"></el-table-column>
                          <el-table-column size="mini" align="center" prop="remarks" show-overflow-tooltip label="备注"></el-table-column>

                        
                    </el-table>
                </div>
          </div>
        <!-- 分页 -->
        <el-pagination
          class="pagination"
          small
          background
          ref="pagination"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="Pagination.currentPage"
          :page-sizes="Pagination.pageSizeList"
          :page-size="Pagination.pageSize"
          :layout="Pagination.layout"
          :total="Pagination.total"
        ></el-pagination>

       
           <el-dialog
            v-el-drag-dialog
            width="700px"
            :title='addText'
             @close = 'dialogClose'
            :visible.sync="addShowB"
            v-if="addShowB"
            :close-on-click-modal="false">
                <el-form  label-width="12rem" :model="xzData"  ref="xzData"  size="mini" :rules="addRules">
                     <el-row>
                        <el-col :span="12">
                          <el-form-item prop="brandName" label="品牌名称：">
                            <el-input maxlength="6" :disabled='disabled'  v-model="xzData.brandName" clearable></el-input>
                          </el-form-item>
                        </el-col>
                        <el-col :span="12">
                          <el-form-item prop="brandCode" label="品牌代码：">
                            <el-input maxlength="6" disabled='true' v-model="xzData.brandCode" clearable></el-input>
                          </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                            <el-form-item  label="是否默认："  prop="isdefault" >
                              <el-radio-group :disabled="disabled"  v-model="xzData.isdefault" >
                                <el-radio label="Y" :disabled='disabled'>是</el-radio>
                                <el-radio label="N" :disabled='disabled' >否</el-radio>
                              </el-radio-group>
                              
                            </el-form-item>
                          </el-col>
                         <el-col :span="12">
                            <el-form-item  label="是否有效："  prop="iseffective" >
                              <el-radio-group :disabled="disabled"  v-model="xzData.iseffective" >
                               <el-radio label="Y" :disabled='disabled' >是</el-radio>
                                <el-radio label="N" :disabled='disabled' >否</el-radio>
                              </el-radio-group>
                             
                            </el-form-item>
                          </el-col>
                    </el-row>


                    <el-row>
                      <el-col :span="24">
                          <el-form-item prop="remarks" label="备注：">
                            <el-input maxlength="32" :disabled='disabled' type="textarea" v-model="xzData.remarks" clearable></el-input>
                          </el-form-item>
                        </el-col>

                    </el-row>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button size='mini'  @click="close">关闭</el-button>
                    <el-button size='mini' type="primary" v-if="see" @click="saveEditor('xzData')">保存</el-button>
                </div>
          </el-dialog>

    <!-- 对话框 批量导入Excel -->
    <el-dialog
      :title="name"
      :visible.sync="openDialog"
      v-if="openDialog"
      v-el-drag-dialog
      :before-close="close"
      :close-on-click-modal="false"
      width="50%"
    >
      <div class="containers">
        <div class="c_file">
          <el-form :model="dialogForm" size="mini" :rules="dialogRule"  ref="dialogForm" label-width="auto">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item prop="cteFilePath" label="货物品牌文件：" >
                  <el-upload
                    class="upload-demo"
                    accept=".xlsx"
                    drag
                    action=""
                    limit="1"
                    :http-request="httpRequest"
                    :on-remove="removeFile"
                  >
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    <div class="el-upload__tip" slot="tip">只能上传.xlsx文件，且不超过500kb</div>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div class="c_msg">

        </div>
      </div>

      <div slot="footer" class="dialog-footer" >
        <el-button  @click="close" size="mini">关闭</el-button>
        <el-button type="primary" @click="save" size="mini">保存</el-button>

      </div>
    </el-dialog>

    <!-- 货物品牌导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>

        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="upload.open = false">取 消</el-button>
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  goodsBrandList, addGoodsBrand, editGoodsBrand, deleteGoodsBrand, 
  // uploadText,
  createCode
} from '@/request/api'
import resizeMixin from '@/mixins/resize'
import paginationMixin from '@/mixins/pagination'
import isAuth from '@/mixins/buttonAuth'
import buttonName from '@/components/buttonName/button-name.vue'
import {importGoodsBrandSer, importTemplate} from '@/request/datAmanagementA/goodsBrand'
import {getToken} from '@/request/http'
export default {
  name: 'router.goodsBrand',
  mixins: [resizeMixin,paginationMixin,isAuth],
  data(){
    return{
      downloadLoading:false,
      from:{
        brandName:'',
      },
      item:{
        item:true,
        itemA:false
      },
 
      maxHeight:-1,
      disabled:false,
      checkedY: true,
      checkedN: false,
      disabledA:false,
      listData:[],
      listDataA:[],
      diong:'E',
      addText:'',
      addShowA:false, // 新增
      addShowB:false, //  编辑
      see:true, //保存按钮
      DetailedData:[], //主列表的数据
      xzData:{},// 传给新增 编辑弹出框的数据
      PageIndexs:'',
      PageSizes:'',
      itemData:[], //当前行数据
      shiList:[], // 下拉框
      departmentList:[],
      openDialog:false, //导入文件弹框

      // 货物品牌导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Token: getToken() },
        // 上传的地址
        url: (process.env.NODE_ENV === 'production' ? '/' : '/proxy/') + 'FTKJWLHYPT/base/importGoodsBrand'
      },
      //表单验证 新增 编辑
      addRules:{

        brandName:[
          { required: true, message: '请输入品牌名称', trigger:'blur'}
        ],

        contactDetails:[
          { required: true, message: '请填写联系人电话', trigger:'blur'},
          {
            pattern: /^[1-9]\d*$/,
            message: '请输入数字',
            trigger: 'blur'
          }
        ],
        auditOpinon:[
          { required: true, message: '请填写审核意见', trigger:'blur'},

        ],
        created:[
          { required: true, message: '请选择仲裁时间', trigger:'blur'},

        ],
        dialogRule:{
          cteFilePath:[{required:true,message:'请选择需要上传的Excel文件',trigger:'change'}],
        },
      },
    }
  },
  created(){
    this.resize = () => {
      this.maxHeight = this.$refs.inner.offsetHeight
    }
  },
  mounted(){
    this.refreshList()

  },
  methods:{
    // 切换大写
    uppercase(key) {
      this.xzData[key] = this.xzData[key].toUpperCase()
    },
    dialogClose() {
      this.itemData = ''
      // this.currentData = ''
      this.refreshList()
    },
    // 列表数据
    getList(currentPage, pageSize, updateTotal) {
      goodsBrandList({
        brandName:this.from.brandName,
        // arbitrationType:this.from.arbitrationType,
        PageIndex: this.Pagination.currentPage.toString(),
        PageSize: this.Pagination.pageSize.toString()
      }).then(res => {
        this.DetailedData = res.data
        updateTotal(Number(res.total))
      })
    },
    // // 点击搜索
    searchType(){
      this.refreshList()
      this.close()
    },
    //新增
    add(){
      let pre='PP'
      
      createCode(pre).then(res => {
        // let t = this
        this.xzData.brandCode=res.msg
      
      }) 
      this.addText='新增'
      this.diong=''
      this.see = true
      this.addShowB=true
      this.disabled= false
      this.disabledA = false
      this.xzData = {

        brandName:'',
        brandCode:'',
    
        remarks:'',
        isdefault:'N',
        iseffective:'Y'
       
      }
    },
    //编辑
    del(){
      if(Object.keys(this.itemData).length){

  
        this.xzData = JSON.parse(JSON.stringify(this.itemData))
        
        this.addText='编辑'
        this.diong='E'
        this.addShowB=true
        this.disabled= false
        this.disabledA = false
        this.see = true

      }else{
        this.$alert('请选择需要编辑的内容', '提示', {
          confirmButtonText: '确定'
        })
        return false
      }
    },
    //删除
    examine(){
      if(Object.keys(this.itemData).length){
        this.$confirm('您确认要删除此内容吗?', '提示', {
          closeOnClickModal: false,

        }).then(() => {
          deleteGoodsBrand({brandId:this.itemData.brandId}).then(res=>{
            if(res.success !== '1'){
              this.$message ({
                type: 'success',
                message: '删除失败'
              })
              return
            }else{
              this.$message ({
                type: 'success',
                message: '删除成功'
              })
             
            }
            this.refreshList()
            this.close()
          })
        })
      }else{
        this.$alert('请选择需要删除的内容', '提示', {
          confirmButtonText: '确定'
        })
        this.refreshList()
        this.close()
        // return false
      
      }
       
    },
    // 生成表格序号的方法
    indexMethod (index) {
      return 1 + index + (Number(this.Pagination.currentPage) - 1) * Number(this.Pagination.pageSize)
    },
    //批量导入货物品牌
    importGoodsBrand(){
      this.openDialog=true
      this.name='批量导入货物品牌'
      this.dialogForm={}
      this.fileList=[]
      this.add=true
    },
    //文件上传
    httpRequest({file}){
      importGoodsBrandSer(file).then(res => {
        this.dialogForm.cteFilePath=res.data.url
        if(res.success=='1'){
          this.$alert('批量导入数据成功！', '提示', {
            confirmButtonText: '确定'
          })
          this.close()
        }
      })
    },

    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = '货物品牌导入'
      this.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.msg)
      })
    },

    // 文件上传中处理
    // eslint-disable-next-line no-unused-vars
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    // eslint-disable-next-line no-unused-vars
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert(response.msg, '导入结果', { dangerouslyUseHTMLString: true })
      this.getList()
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },

    removeFile(){
      this.dialogForm.cteFilePath=null
    },
    //下载
    handleDownload(){
      // var timestamp = (new Date()).valueOf();
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          '品牌名称', '品牌代码']
        const filterVal = [
          'brandName', 'brandCode']
        //要是导入数据的话 this.departmentList 换成存放表格数据的数组，不导入数据使用this.departmentList空数组
        const list = this.departmentList //空数组
        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          // filename: timestamp,
          filename: '模板',
          autoWidth: true
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v,index) =>
        filterVal.map(j => {
          if(j === 'isdefault'){
            if(v[j] === 'Y'){
              return '是'
            }else{
              return '否'
            }
          }
          if('index' === j){
            return index+1
          }
          return v[j]
        })
      )
    },
    //双击查看
    rowdbClickA(row){
      this.addText='查看'
      this.addShowB=true
      this.see=false
      this.xzData=row
      this.disabled= true
      this.disabledA= true
    },
    //新增 编辑  点击保存
    saveEditor(xzData){
      // console.log( this.$refs[xzData])
      this.$refs[xzData].validate((valid) => {
        if (valid) {
          if (this.diong ==='E') {
            console.log(this.xzData)
            editGoodsBrand(this.xzData).then(res=>{
              if(res.success !=='1'){
                this.$message ({
                  type: 'success',
                  message: '编辑失败'
                })
              }else{
                // this.xzData = []
                this.$message ({
                  type: 'success',
                  message: '编辑成功'
                })
                this.close()
                this.refreshList()
              }
            })
          }else{
            addGoodsBrand(this.xzData).then(res=>{
              if(res.success !== '1'){
                this.$message ({
                  type: 'success',
                  message: '添加失败'
                })
              }else{
                this.$message ({
                  type: 'success',
                  message: '添加成功'
                })
                this.close()
                this.refreshList()
                this.$refs[xzData].resetFields()
              }
            })

          }
        } else {
          return false
        }
      })
    },
    // 关闭弹出框
    close(){
      this.addShowA=false
      this.addShowB=false
      this.openDialog = false
      this.itemData = ''
      this.refreshList()
    },
    //当前行数据
    rowClick(row){
      // console.log(row)
      this.itemData = row
    },
    //调取父组件方法
    clickEventDom(item){
      if(item.mdlCode === 'add'){
        this.add()
      }else if(item.mdlCode === 'examine'){
        this.examine()
      }else if(item.mdlCode === 'del'){
        this.del()
      }else if(item.mdlCode === 'handleImport'){
        this.handleImport()
      }else if(item.mdlCode === 'handleDownload'){
        this.handleDownload()
      }
    }
  },
  components: {
    buttonName
  },
}
</script>

<style  lang="scss" scoped>
.el-select {
  width: 100%;
}
.app-container {
  height: 100%;
  width: 100%;
  position: relative;
  display: flex;
  flex-direction: column;
  .table {
    flex: 1;
    position: relative;
    overflow: hidden;
    .inner {
      width: 100%;
      height: 100%;
      overflow: hidden;
    }
    .el-pagination {
      height: 4rem;
      flex: 0 0 auto;
      margin: 1rem 0;
    }
  }
}
::v-deep .el-textarea__inner{
    height: 100px;
 }
  .containers{
    width:900px;
    height:500px;
    border:1px solid #ccc;
    .c_file{
      padding-top: 30px;
      float: left;
      width:380px;
      height:500px;
    }
    .c_msg{
      width:380px;
      height:500px;
      margin-left:40px;
      float:left;
    }
  }
.el-upload__tip[data-v-2d30027a] {
  font-size: 12px;
  color: #606266;
  margin-top: 7px;
  width: 260px;
}


</style>
